package com.example.sys.ai.service;

import cn.hutool.http.HttpRequest;
import com.example.core.constant.Constant;
import com.example.sys.ai.dto.Company;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.List;

@Service
public class SysTianYanChaServiceImpl implements SysTianYanChaService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${tyc.token}")
    private String token;

    //默认页数
    private static final int pageSize = 20;

    //默认页码
    private static final int pageNum = 1;

    /***
     * 查询基本信息
     */
    public static final String _ORG_BASE_INFO_URL_ = "http://open.api.tianyancha.com/services/open/ic/baseinfo/normal";

    /***
     * 关键字搜索列表
     */
    public static final String _ORG_SEARCH_INFO_URL_ = "http://open.api.tianyancha.com/services/open/search/2.0";

    /***
     * 天眼查查询公司信息
     * @param keyWord 关键字 一般是公司名，统一社会信用代码
     * @return Company 返回公司信息
     */
    @Override
    public Company getByCompany(String keyWord) throws Exception {
        String url = _ORG_BASE_INFO_URL_ + "?keyword=" + URLEncoder.encode(keyWord, Constant.UTF8);
        String json = HttpRequest.get(url).header("Authorization", token).execute().body();
        return Company.toCompany(json);
    }


    /***
     * 根据关键字查询公司列表
     * @param keyWord 关键字
     * @return
     * @throws Exception
     */
    @Override
    public List<Company> getByCompanyList(String keyWord) throws Exception {
        String url = _ORG_SEARCH_INFO_URL_ + "?word=" + URLEncoder.encode(keyWord, "UTF-8") + "&pageSize=" + pageSize + "&pageNum=" + pageNum;
        String json = HttpRequest.get(url).header("Authorization", token).execute().body();
        return Company.toCompanyList(json);
    }
}
